import Mock from "mockjs"
// mock 插件 可以拦截我们前端的接口请求
import city from "./citydata.json"

// 递归查找
function dg_find(origin: any, id: any): any {
  // 第一层找不到，就递归式找
  for (var i = 0; i < origin.length; i++) {
    if (origin[i].value === id) {
      return origin[i].children?.map((item: any) => {
        return {
          id: item.value,
          code: item.value,
          extName: item.value,
        }
      })
    } else if (origin[i].children) {
      let result = dg_find(origin[i].children, id)
      if (result) {
        return result
      }
    } else {
      return false;
    }
  }
}

export default () => {
  Mock.mock("/antd/city", "post", function (req: any) {

    let { id } = JSON.parse(req.body) || { id: false }

    // id不在给省的数据，有id就给查找id的数据
    if (!id) {
      return city.map((item: any) => {
        return {
          id: item.value,
          code: item.value,
          extName: item.value,
        }
      })
    }
    return dg_find(city, id)
    // 如果有id，找到id的数据，把它的孩子返回出去
  })
}